package yxy.game.pm2.command.temple;

import yxy.cherry.battle.module.Position;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Format;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.TempleMessage;
import yxy.game.pm2.module.hero.FormatHandle;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.resonate.ResonateHandle;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/** 置换神殿 置换神殿置换 */
@MessageType(proto = Command.TempleChange, classtype = TempleMessage.TempleChangeRequest.class)
public class CMD_TempleChange extends Command<TempleMessage.TempleChangeRequest> {

	@Override
	public void execute(MessageSource messageSource, TempleMessage.TempleChangeRequest request) {
		String playerCode = messageSource.getTag();
		String heroCode = request.getHero();
		List<String> expend = request.getTargetsList();
		boolean isBackMagic = request.hasIsBackMagic();
		TempleMessage.TempleChangeResponse.Builder response = TempleMessage.TempleChangeResponse.newBuilder();
		try {


			//阵容上的武将不能置换
			FormatHandle formatHandle = new FormatHandle();
			Format format = Format.get(playerCode, Format.FormatType.普通);
			Map<Position, String> heroMap = formatHandle.formatCodes(playerCode, format);
			for (Map.Entry<Position, String> entry : heroMap.entrySet()) {
				if(heroCode.equals(entry.getValue())){
					send(messageSource, response, Result.TempleHeroCantSelectFormatHero);//阵容上的武将不能置换
					return;
				}
			}


			//共鸣的武将不能置换神殿置换
			ArrayList<String> list = new ArrayList<>();
			list.addAll(expend);
			list.add(heroCode);
			Result resultForResonate = ResonateHandle.heroIsResonateHero(list, playerCode);
			if(!resultForResonate.equals(Result.Success)){
				send(messageSource, response, resultForResonate);
				return;
			}

			Result result = new HeroHandle().templeChange(playerCode, heroCode, expend, response,isBackMagic);
			send(messageSource, response, result);

			//判断如果消耗的是共鸣系统场上的武将，对应操作
			if(result.equals(Result.Success)) {
				ResonateHandle.heroIsAboveHeroAndResolve(list, playerCode);
			}

		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);

		}
	}

	private void send(MessageSource messageSource, TempleMessage.TempleChangeResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}